package com.wxm.controller;

import com.wxm.jwt.client.properties.JWTFileAuthClient;
import com.wxm.jwt.client.util.JWTAuthClientFactory;
import com.wxm.jwt.client.util.JwtTokenClientUtil;
import com.wxm.jwt.service.util.JWTAuthServiceFactory;
import com.wxm.jwt.service.properties.JWTFileAuthService;
import com.wxm.jwt.service.util.JwtTokenServiceUtil;
import com.wxm.vo.JwtUserInfo;
import com.wxm.log.core.R;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @author: wxm
 * @Date: 2021/10/6
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private final File priFile = new ClassPathResource("pri.key").getFile();
    private final File pubFile = new ClassPathResource("pub.key").getFile();

    public UserController() throws IOException {
    }

    /**
     * 服务端 生成Token
     * @return R.ok(token)
     * @throws IOException
     */
    @GetMapping("/login")
    public R login() throws IOException {
        //使用服务端进行生成Token
        JwtTokenServiceUtil utils = new JwtTokenServiceUtil(() -> JWTAuthServiceFactory.buildJWTAuthClient(JWTFileAuthService.class, pubFile, priFile, 500));
        String token = utils.generateToken(new JwtUserInfo(1, "admin", 1).toJsonObject(),null);
        return R.ok(token);
    }

    /**
     * 服务端 解析Token
     * @return R.ok(JwtUserInfo)
     * @throws IOException
     */
    @GetMapping("/service-verify")
    public R serviceVerify(@RequestParam("token") String token){
        //使用服务端校验Token
        JwtTokenServiceUtil utils = new JwtTokenServiceUtil(() -> JWTAuthServiceFactory.buildJWTAuthClient(JWTFileAuthService.class, pubFile, priFile, 500));
        return R.ok(utils.getUserInfo(token,JwtUserInfo.class));
    }

    /**
     * 客户端 解析Token
     * @return R.ok(JwtUserInfo)
     * @throws IOException
     */
    @GetMapping("/client-verify")
    public R clientVerify(@RequestParam("token") String token){
        //使用客户端校验Token
        JwtTokenClientUtil utils = new JwtTokenClientUtil(() -> JWTAuthClientFactory.buildJWTAuthClient(JWTFileAuthClient.class, pubFile));
        return R.ok(utils.getUserInfo(token,JwtUserInfo.class));
    }
}
